import React from 'react';
import PropTypes from 'prop-types';
import { history } from 'umi';
import styles from './index.less';

// 为了解决浏览器右键新标签打开时路径有问题
const LinkTo = ({ to, query, onClick, state, isDefault, ...rest }) => {
    let queryStr = '';
    Object.keys(query).forEach((prop, index) => {
        if (index === 0) queryStr += '?';
        queryStr += `${prop}=${query[prop]}`;
        if (index !== Object.keys(query).length - 1) {
            queryStr += '&';
        }
    });
    const finalQuery = () => {
        if (query) {
            return {
                pathname: to,
                query,
                state
            };
        }
        return to;
    };
    return (
        <a
            href={query ? `${to}${queryStr}` : to}
            className={isDefault === true ? styles.normal : ''}
            onClick={e => {
                if (rest.target) return;
                e.preventDefault();
                if (onClick) {
                    onClick(e, finalQuery());
                } else {
                    history.push(finalQuery());
                }
            }}
            {...rest}
        >
            {rest.children}
        </a>
    );
};

LinkTo.propTypes = {
    to: PropTypes.string.isRequired,
    query: PropTypes.object
};

LinkTo.defaultProps = {
    query: {}
};

export default LinkTo;
